﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Shell;
using System.Xml;
using Microsoft.Win32;

using IWshRuntimeLibrary;
using Shell32;
using File = System.IO.File;

namespace TaskBarLauncher
{
    /// <summary>
    /// Logique d'interaction pour Window1.xaml
    /// </summary>
    public partial class MyWindow
    {
        private Dictionary<string, string> _variables = new Dictionary<string, string>();

        public MyWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load("config.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            JumpList jumpList = JumpList.GetJumpList(Application.Current);
            XmlNodeList root = doc.LastChild.ChildNodes;

            foreach (XmlNode var in root.GetNode("Variables"))
            {
                switch (var.Name)
                {
                    case "Registry":
                        _variables.Add(var.GetAttribute("name"), Registry.GetValue(var.GetAttribute("key"), var.GetAttribute("value"), var.GetAttribute("defaultValue")) as string);
                        break;
                    case "String":
                        _variables.Add(var.GetAttribute("name"), var.GetAttribute("string"));
                        break;
                }
            }

            foreach (XmlNode cat in root.GetNode("TaskBar"))
            {
                foreach (XmlNode elem in cat.ChildNodes)
                {
                    JumpTask jumpTask = new JumpTask();

                    switch (elem.Name)
                    {
                        case "Command":
                            jumpTask.ApplicationPath = @"cmd.exe";
                            jumpTask.Arguments = "/c " + Read(elem, "command");
                            break;
                        case "Folder":
                            jumpTask.ApplicationPath = @"C:\Windows\explorer.exe";
                            jumpTask.Arguments = Read(elem, "folder");
                            break;
                        case "Task":
                            jumpTask.ApplicationPath = Read(elem, "filename");
                            jumpTask.Arguments = Read(elem, "args");
                            break;
                        default:
                            continue;
                    }

                    string icon = Read(elem, "iconPath", jumpTask.ApplicationPath);
                    if (!icon.Contains("\\"))
                    {
                        icon = Path.Combine(Directory.GetCurrentDirectory(), icon);
                    }

                    jumpTask.IconResourcePath = icon;
                    jumpTask.IconResourceIndex = Read(elem, "iconIndex").ToInt(0);
                    jumpTask.Description = Read(elem, "desc");
                    jumpTask.WorkingDirectory = Read(elem, "dir", Directory.GetParent(jumpTask.ApplicationPath).FullName);
                    jumpTask.Title = Read(elem, "name");
                    jumpTask.CustomCategory = cat.Name;

                    jumpList.JumpItems.Add(jumpTask);
                }
            }
            jumpList.Apply();

            try
            {
                Process current = Process.GetCurrentProcess();

                // Create the shortcut
                string lnk = Environment.GetEnvironmentVariable("APPDATA") + @"\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\" + current.ProcessName + ".lnk";

                IWshShortcut shortcut = new WshShellClass().CreateShortcut(lnk) as IWshShortcut;
                shortcut.TargetPath = current.MainModule.FileName;
                shortcut.WorkingDirectory = Directory.GetCurrentDirectory();

                File.Delete(lnk);
                shortcut.Save();
                PinToTaskbar(lnk);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Close();
        }

        private static void PinToTaskbar(string link)
        {
            string tempFile = Path.GetDirectoryName(link) + @"\pin.vbs";
            File.WriteAllText(tempFile, PinUnpinScript);
                
            // Épingler à la barre des tâches
            string[] languages = { "Épingler à la barre des tâches", "Pin to Taskbar" };
            foreach (var language in languages)
            {
                using (var scriptProc = Process.Start(new ProcessStartInfo
                    {
                        FileName = @"cscript",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        WindowStyle = ProcessWindowStyle.Hidden,
                        Arguments = string.Format("//B //Nologo \"{0}\" \"{1}\" \"{2}\"", tempFile, link, language)
                    }))
                {
                    scriptProc.WaitForExit();
                    scriptProc.Close();
                }
            }
            File.Delete(tempFile);
        }

        private static readonly string PinUnpinScript =
            @"Set oArgs = WScript.Arguments" + Environment.NewLine +
            @"Set objShell = CreateObject(""Shell.Application"")" + Environment.NewLine +
            @"Set filesystem = CreateObject(""scripting.Filesystemobject"")" + Environment.NewLine +
            @"Set objFolder = objShell.Namespace(filesystem.GetParentFolderName(oArgs(0)))" + Environment.NewLine +
            @"Set objFolderItem = objFolder.ParseName(filesystem.GetFileName(oArgs(0)))" + Environment.NewLine +
            @"Set colVerbs = objFolderItem.Verbs" + Environment.NewLine +
            @"For Each objVerb in colVerbs" + Environment.NewLine +
            @"  If Replace(objVerb.name, ""&"", """") = oArgs(1) Then objVerb.DoIt" + Environment.NewLine +
            @"Next";

        string Read(XmlNode node, string key, string defaultValue = "")
        {
            return _variables.Aggregate(
                node.GetAttribute(key, defaultValue), 
                (current, var) => current.Replace("[#" + var.Key + "#]", var.Value));
        }
    }
}
